package com.kalvan.admin.system.controller;


import com.github.pagehelper.Page;
import com.kalvan.core.exception.BizException;
import com.kalvan.core.mybatis.PageInfo;
import com.kalvan.core.utils.BeanUtils;
import com.kalvan.core.utils.Sysdate;
import com.kalvan.core.utils.ValidationUtil;
import com.kalvan.core.valid.Add;
import com.kalvan.core.valid.Edit;
import com.kalvan.web.controller.BaseController;
import com.kalvan.web.excel.ExcelUtil;
import com.kalvan.web.exception.AdminReturnCode;
import com.kalvan.web.log.LogType;
import com.kalvan.web.log.annotation.SysLog;
import com.kalvan.web.servlet.annotation.Permission;
import com.kalvan.web.servlet.response.R;
import com.kalvan.commons.constant.LogGroup;
import com.kalvan.commons.db.system.model.Demo;
import com.kalvan.commons.dto.system.DemoImport;
import com.kalvan.admin.system.service.DemoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 测试流水表Controller
 *
 * @author kalvan
 */
@SysLog(group = LogGroup.DEMO)
@Api(tags = {"测试流水表"})
@RestController
@RequestMapping("system/demo")
@Slf4j
public class DemoController extends BaseController {
    @Resource
    DemoService demoService;

    /**
     * 分页查询
     *
     * @param params 查询参数
     * @return R
     */
    @ApiOperation("分页查询")
    @PostMapping("list")
    @Permission("admin:system:demo:list")
    public R list(PageInfo pageInfo, @RequestParam Map<String, String> params) {
        Page<Demo> data = demoService.queryPage(pageInfo, params);
        return R.ok().putPage(data);
    }

    /**
     * 汇总查询
     *
     * @param params 查询参数
     * @return R
     */
    @ApiOperation("汇总查询")
    @PostMapping("sum")
    @Permission("admin:system:demo:sum")
    public R sum(@RequestParam Map<String, String> params) {
        Map<String, String> data = demoService.querySum(params);
        return R.ok().putData(data);
    }

    /**
     * 根据主键查询详情
     *
     * @param id 主键
     * @return R
     */
    @ApiOperation("主键查询")
    @GetMapping("info/{id}")
    @Permission("admin:system:demo:info")
    public R info(@PathVariable("id") Long id) {
        Demo demo = demoService.findById(id);
        if (demo == null) {
            throw new BizException(AdminReturnCode.REQUEST_ILLEGAL);
        }
        return R.ok().putData(demo);
    }

    private static final int DOWNLOAD_MAX_COUNT=20000;

    /**
     * 下载
     *
     * @param params 查询参数
     * @param response response
     * @throws Exception 抛出异常拦截器统一处理
     */
    @ApiOperation("下载测试流水表")
    @PostMapping("download")
    @Permission("admin:system:demo:download")
    public void download(@RequestParam Map<String, String> params, HttpServletResponse response) throws Exception {
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPage(1);
        pageInfo.setLimit(DOWNLOAD_MAX_COUNT);
        Page<Demo> data = demoService.queryPage(pageInfo, params);
        String filename = "测试流水表";
        if (data.getTotal() > DOWNLOAD_MAX_COUNT) {
            throw new BizException(AdminReturnCode.PARAM_REGION_OVER.formatDesc("下载条数", DOWNLOAD_MAX_COUNT));
        }
        filename = filename + Sysdate.getTimeStr(true);
        ExcelUtil.download(filename, response, Demo.class, data);
    }

    /**
     * 新增测试流水表
     *
     * @param demoImport demoImport
     * @return R
     */
    @SysLog(remark = "新增测试流水表", type = LogType.ADD)
    @ApiOperation("新增测试流水表")
    @PostMapping("add")
    @Permission("admin:system:demo:add")
    public R add(@Validated({Add.class}) DemoImport demoImport) {
        demoService.add(BeanUtils.newAndCopy(demoImport,Demo.class));
        return R.ok();
    }

    /**
     * 测试流水表导入模板下载
     *
     * @param response response
     * @throws Exception 抛出异常拦截器统一处理
     */
    @ApiOperation("测试流水表导入模板下载")
    @GetMapping("downloadTemplate")
    @Permission("admin:system:demo:upload")
    public void downloadTemplate(HttpServletResponse response) throws Exception {
        ExcelUtil.downloadTemplate(templateRootPath + "com/kalvan/admin/测试流水表-模板.xls", response);
    }

    /**
     * 导入测试流水表
     *
     * @param file file
     * @return R
     */
    @SysLog(remark = "导入测试流水表", type = LogType.IMPORT)
    @ApiOperation("导入测试流水表")
    @PostMapping("upload")
    @Permission("admin:system:demo:upload")
    public R upload(@RequestParam MultipartFile file) throws Exception {
        List<DemoImport> importList = ExcelUtil.importExcel(file, 1, 1, DemoImport.class);
        for (DemoImport demoImport : importList) {
            String error = ValidationUtil.validation(demoImport, new Class[]{Add.class});
            if (StringUtils.isNotBlank(error)) {
                throw new BizException(AdminReturnCode.PARAM_ILLEGAL.formatDesc(error));
            }
            demoService.add(BeanUtils.newAndCopy(demoImport,Demo.class));
        }
        return R.ok(AdminReturnCode.SUCCESS_IMPORT.getFormatDesc(importList.size()));
    }

    /**
     * 修改测试流水表
     *
     * @param demoImport demoImport
     * @return R
     */
    @SysLog(remark = "修改测试流水表", type = LogType.EDIT)
    @ApiOperation("修改测试流水表")
    @PostMapping("edit")
    @Permission("admin:system:demo:edit")
    public R edit(@Validated({Edit.class}) DemoImport demoImport) {
        if (demoImport.getId() == null) {
            return R.error(AdminReturnCode.REQUEST_ILLEGAL.getMsg());
        }
        demoService.edit(BeanUtils.newAndCopy(demoImport,Demo.class));
        return R.ok();
    }

    /**
     * 根据主键删除测试流水表
     *
     * @param ids ids
     * @return R
     */
    @SysLog(remark = "删除测试流水表", type = LogType.DELETE)
    @ApiOperation("删除测试流水表")
    @PostMapping("delete")
    @Permission("admin:system:demo:delete")
    public R delete(Long[] ids) {
        if (ArrayUtils.isEmpty(ids)) {
            return R.error(AdminReturnCode.REQUEST_ILLEGAL.getMsg());
        }
        int num = demoService.deleteBatch(ids);
        return R.ok(AdminReturnCode.SUCCESS_DELETE.getFormatDesc(num));
    }

    @SysLog(remark = "审核测试流水表", type = LogType.AUDITING)
    @ApiOperation("审核测试流水表")
    @PostMapping("auditing")
    @Permission("admin:system:demo:auditing")
    public R auditing(Long[] ids, boolean pass) {
        if (ArrayUtils.isEmpty(ids)) {
            return R.error(AdminReturnCode.REQUEST_ILLEGAL.getMsg());
        }
        int num = demoService.auditingBatch(ids, pass);
        return R.ok(AdminReturnCode.SUCCESS_AUDITING.getFormatDesc(num));
    }

    @ApiOperation("测试")
    @Permission("admin:system:demo:test")
    @PostMapping("test")
    public R test(Long[] ids) {
        //TODO 业务检查和处理
        if (ArrayUtils.isEmpty(ids)) {
            return R.error(AdminReturnCode.REQUEST_ILLEGAL.getMsg());
        }
        return R.ok();
    }

}
